<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模型边界线验证</title>
    <script src="https://cesium.com/downloads/cesiumjs/releases/1.95/Build/Cesium/Cesium.js"></script>
    <link href="https://cesium.com/downloads/cesiumjs/releases/1.95/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
    <style>
        #cesiumContainer {
            width: 100%;
            height: 100vh;
            position: relative;
        }
        #controls {
            position: absolute;
            top: 10px;
            left: 10px;
            background: rgba(255, 255, 255, 0.9);
            padding: 10px;
            border-radius: 5px;
            z-index: 1000;
        }
        #debugInfo {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(255, 255, 255, 0.9);
            padding: 10px;
            border-radius: 5px;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <div id="cesiumContainer"></div>
    <div id="controls">
        <div>
            <label>选择模文件（.gltf/.glb）:</label>
            <input type="file" id="fileUpload" accept=".gltf,.glb">
        </div>
        <div>
            <label>纬度:</label>
            <input type="number" id="latitudeInput" value="39.9087202" step="0.000001">
        </div>
        <div>
            <label>经度:</label>
            <input type="number" id="longitudeInput" value="116.3974799" step="0.000001">
        </div>
        <div>
            <label>高度(米):</label>
            <input type="number" id="heightInput" value="10">
        </div>
        <div>
            <label>旋转角度X(度):</label>
            <input type="number" id="rotationXInput" value="0">
        </div>
        <div>
            <label>旋转角度Y(度):</label>
            <input type="number" id="rotationYInput" value="0">
        </div>
        <div>
            <label>旋转角度Z(度):</label>
            <input type="number" id="rotationZInput" value="0">
        </div>
        <div>
            <label>缩放比例:</label>
            <input type="number" id="scaleInput" value="1.0" step="0.1">
        </div>
        <button onclick="loadModelAndBoundary()">加载模型和边界线</button>
    </div>
    <div id="debugInfo"></div>

    <script>
        // 全局变量定义
        let viewer;
        let modelEntity = null;
        let boundaryEntity = null;

        // 初始化 Cesium
        function initCesium() {
            // 设置 Cesium Ion token
            Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIzNzFlNTg1MC0wOTA0LTQzYzYtOTBjZi05MjIzZjU2NTkzZGQiLCJpZCI6MTE4ODE3LCJpYXQiOjE2NzE1MDY2NjF9.yGR3CbS6VQp2s6Y9NHWOIKq8qKL0sWLZZBZ9eP02Ags";
            
            viewer = new Cesium.Viewer('cesiumContainer', {
                baseLayerPicker: false,
                geocoder: false,
                navigationHelpButton: false,
                homeButton: false,
                sceneModePicker: false,
                animation: false,
                timeline: false,
                fullscreenButton: false,
                infoBox: false,
                selectionIndicator: false,
                terrainProvider: new Cesium.EllipsoidTerrainProvider(), // 使用椭球体地形
                requestRenderMode: true,  // 仅在需要时渲染
                maximumRenderTimeChange: Infinity,
                scene3DOnly: true,  // 只使用3D模式
                contextOptions: {
                    webgl: {
                        alpha: true,
                        depth: true,
                        stencil: true,
                        antialias: true,
                        premultipliedAlpha: true,
                        preserveDrawingBuffer: true
                    }
                }
            });

            // 设置初始视角
            viewer.camera.setView({
                destination: Cesium.Cartesian3.fromDegrees(
                    parseFloat(document.getElementById('longitudeInput').value),
                    parseFloat(document.getElementById('latitudeInput').value),
                    100
                ),
                orientation: {
                    heading: 0.0,
                    pitch: Cesium.Math.toRadians(-30),
                    roll: 0.0
                }
            });
        }

        // 加载模型和边界线
        async function loadModelAndBoundary() {
            try {
                const fileInput = document.getElementById('fileUpload');
                const file = fileInput.files[0];
                if (!file) {
                    throw new Error('请先选择模型文件');
                }

                console.log('准备加载模型:', {
                    fileName: file.name,
                    fileSize: file.size,
                    fileType: file.type
                });

                const latitude = parseFloat(document.getElementById('latitudeInput').value);
                const longitude = parseFloat(document.getElementById('longitudeInput').value);
                const height = parseFloat(document.getElementById('heightInput').value);
                const rotationX = parseFloat(document.getElementById('rotationXInput').value);
                const rotationY = parseFloat(document.getElementById('rotationYInput').value);
                const rotationZ = parseFloat(document.getElementById('rotationZInput').value);
                const scale = parseFloat(document.getElementById('scaleInput').value);

                // 清除现有实体
                viewer.entities.removeAll();

                // 准备上传数据
                const formData = new FormData();
                formData.append('file', file);
                formData.append('latitude', latitude.toString());
                formData.append('longitude', longitude.toString());
                formData.append('height', height.toString());
                formData.append('rotationX', rotationX.toString());
                formData.append('rotationY', rotationY.toString());
                formData.append('rotationZ', rotationZ.toString());
                formData.append('scale', scale.toString());

                console.log('开始上传，参数：', {
                    latitude: latitude,
                    longitude: longitude,
                    height: height,
                    rotationX: rotationX,
                    rotationY: rotationY,
                    rotationZ: rotationZ,
                    scale: scale
                });

                const response = await fetch('http://localhost:8080/api/model/upload', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error(`上传失败: ${response.status}`);
                }

                const result = await response.json();
                console.log('服务器返回数据:', result);

                // 修改模型加载部分
                const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
                    Cesium.Cartesian3.fromDegrees(longitude, latitude, height)
                );

                // 应用旋转变换
                const rotationMatrix = Cesium.Matrix4.fromRotationTranslation(
                    Cesium.Matrix3.fromHeadingPitchRoll(
                        new Cesium.HeadingPitchRoll(
                            Cesium.Math.toRadians(rotationZ),
                            Cesium.Math.toRadians(rotationX),
                            Cesium.Math.toRadians(rotationY)
                        )
                    )
                );
                Cesium.Matrix4.multiply(modelMatrix, rotationMatrix, modelMatrix);

                // 使用 Model.fromGltf 加载模型
                const model = viewer.scene.primitives.add(Cesium.Model.fromGltf({
                    url: result.modelUrl,
                    modelMatrix: modelMatrix,
                    scale: scale,
                    minimumPixelSize: 128,
                    maximumScale: 20000,
                    debugShowBoundingVolume: true
                }));

                // 监听模型加载完成事件
                model.readyPromise.then(function(model) {
                    console.log('模型加载成功');
                    
                    // 调整视角到模型
                    viewer.camera.flyTo({
                        destination: Cesium.Cartesian3.fromDegrees(
                            longitude,
                            latitude,
                            height + 100
                        ),
                        orientation: {
                            heading: Cesium.Math.toRadians(0),
                            pitch: Cesium.Math.toRadians(-30),
                            roll: 0
                        },
                        duration: 1
                    });
                }).catch(function(error) {
                    console.error('模型加载失败:', error);
                });

                // 修改边界线处理部分
                if (result.boundary && result.boundary.features) {
                    const coordinates = result.boundary.features[0].geometry.coordinates[0];
                    const boundaryHeight = height / 2;  // 边界线高度为模型高度的一半
                    
                    const positions = coordinates.map(coord => 
                        Cesium.Cartesian3.fromDegrees(coord[0], coord[1], boundaryHeight)  // 使用一半高度
                    );

                    // 添加边界线
                    boundaryEntity = viewer.entities.add({
                        polyline: {
                            positions: positions,
                            width: 3,
                            material: new Cesium.PolylineDashMaterialProperty({
                                color: Cesium.Color.YELLOW
                            })
                        }
                    });

                    // 添加半透明多边形
                    viewer.entities.add({
                        polygon: {
                            hierarchy: new Cesium.PolygonHierarchy(positions),
                            material: Cesium.Color.RED.withAlpha(0.3),
                            height: boundaryHeight  // 使用一半高度
                        }
                    });

                    // 调整视角以显示整个场景
                    const boundingSphere = Cesium.BoundingSphere.fromPoints(positions);
                    viewer.camera.flyToBoundingSphere(boundingSphere, {
                        duration: 1.5,
                        offset: new Cesium.HeadingPitchRange(
                            0,
                            Cesium.Math.toRadians(-45),
                            boundingSphere.radius * 2.0
                        )
                    });
                }

            } catch (error) {
                console.error('完整错误信息:', error);
                document.getElementById('debugInfo').innerText = `
错误详情:
- 消息: ${error.message}
- 堆栈: ${error.stack}
- 类型: ${error.name}
                `;
            }
        }

        // 初始化
        initCesium();
    </script>
</body>
</html> 